package com.qf.homework.dao.impl;

import com.qf.homework.dao.UserDao;
import com.qf.homework.entity.User;
import com.qf.homework.utils.DBManager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    @Override
    public User getUserByUsername(String username) throws SQLException {
        Connection connection = DBManager.getConnection();
        String sql="select username, password, uid,is_delete from table_user where username=?";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,username);
        ResultSet resultSet = ps.executeQuery();
        User user=null;
        if (resultSet.next())
        {
            String uname = resultSet.getString(1);
            String pass = resultSet.getString(2);
            int uid = resultSet.getInt(3);
            int isDelete = resultSet.getInt(4);
            user=new User(uname,pass,uid,isDelete);
        }
        DBManager.close(resultSet,ps,connection);
        return user;
    }

    @Override
    public int register(String username, String password) throws SQLException {
        int res=0;
        Connection connection = DBManager.getConnection();
        String sql="insert into table_user(username,password) values(?,?)";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,username);
        ps.setString(2,password);
        res = ps.executeUpdate();
        DBManager.close(ps,connection);
        return res;
    }

}
